<?php

class Default_IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $translate= new Zend_Translate(
        array(
        'adapter' => 'tmx',
        'content' => APPLICATION_PATH.'/configs/language.tmx',
        'locale'  => 'en'
    	));
    	echo $translate->_("message1");
    	//$em = Zend_Registry::get('doctrine');
    	//$this->em->flush();

    }
   
    public function checkloginAction()
    {
    	$this->_helper->layout->disableLayout();
    	$username = $this->getRequest()->getParam("user");
    	$password = $this->getRequest()->getParam("pass");
    	$user = new Default_Model_DbTable_User();
    	if($user->login($username, md5($password)))
    	{
    		$session= new Zend_Session_Namespace("user");
    		$session->id=$username;
    		echo '1';
    	}else echo '0';
    }
    
	public function changelangAction(){
		$lang= $this->getRequest()->getParam("lang");		
		$this->_helper->layout->disableLayout();
		if(isset($lang))
		{
			$session = new Zend_Session_Namespace();
			$session->lang=$lang;
			echo '1';
		}else echo '0';
	}
	public function configAction()
	{
		$config= new Zend_Session_Namespace();
		$this->_helper->layout->disableLayout();
		# if windows_live_channel requested, we return our windows_live WRAP_CHANNEL_URL
		if( isset( $_REQUEST["get"] ) && $_REQUEST["get"] == "windows_live_channel" )
		{
			echo 
				file_get_contents( $_SERVER["DOCUMENT_ROOT"] . "/../library/Hybrid/resources/windows_live_channel.html" ); 
	
			die();
		}
	
		# if openid_policy requested, we return our policy document  
		if( isset( $_REQUEST["get"] ) && $_REQUEST["get"] == "openid_policy")
		{
			echo 
				file_get_contents( $_SERVER["DOCUMENT_ROOT"] . "/../library/Hybrid/resources/openid_policy.html" ); 
	
			die();
		}
	
		# if openid_xrds requested, we return our XRDS document 
		if( isset( $_REQUEST["get"] ) && $_REQUEST["get"] == "openid_xrds" )
		{
			header("Content-Type: application/xrds+xml");
	
			echo str_replace
				(
					"{RETURN_TO_URL}", 
					Hybrid_Auth::getCurrentUrl( false ) ,
					file_get_contents( $_SERVER["DOCUMENT_ROOT"] . "/../library/Hybrid/resources/openid_xrds.xml" )
				); 
	
			die();
		} 
	
		# if we get a hauth.start or hauth.done
		if( isset( $_REQUEST["hauth_start"] ) || isset( $_REQUEST["hauth_done"] ) )
		{
			# init Hybrid_Auth
			try{ 
				// check if Hybrid_Auth session already exist
				if( ! isset( $_SESSION["HA::CONFIG"] ) ): 
					header("HTTP/1.0 404 Not Found");
	
					die( "Sorry, this page cannot be accessed directly!" );
				endif; 
	
				Hybrid_Auth::initialize( unserialize( $_SESSION["HA::CONFIG"] ) ); 
			}
			catch( Exception $e )
			{ 
				Hybrid_Logger::error( "Endpoint: Error while trying to init Hybrid_Auth" ); 
	
				header("HTTP/1.0 404 Not Found");
	
				die( "Oophs. Error!" );
			}
	
			Hybrid_Logger::info( "Enter Endpoint" ); 
	
			# define:endpoint step 3.
			# yeah, why not a switch!
			if( isset( $_REQUEST["hauth_start"] ) && $_REQUEST["hauth_start"] )
			{
				$provider_id = trim( strip_tags( $_REQUEST["hauth_start"] ) );
	
				# check if page accessed directly
				if( ! Hybrid_Auth::storage()->get( "hauth_session.$provider_id.hauth_endpoint" ) )
				{
					Hybrid_Logger::error( "Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!" );
	
					header("HTTP/1.0 404 Not Found");
	
					die( "Sorry, this page cannot be accessed directly!" );
				}
	
				# define:hybrid.endpoint.php step 2.
				$hauth = Hybrid_Auth::setup( $provider_id );
	
				# if REQUESTed hauth_idprovider is wrong, session not created, or shit happen, etc. 
				if( ! $hauth )
				{
					Hybrid_Logger::error( "Endpoint: Invalide parameter on hauth_start!" ); 
					
					header("HTTP/1.0 404 Not Found");
	
					die( "Invalide parameter! Please return to the login page and try again." );
				}
	
				try
				{ 
					Hybrid_Logger::info( "Endpoint: call adapter [{$provider_id}] loginBegin()" );
					
					$hauth->adapter->loginBegin();
				}
				catch( Exception $e )
				{
					Hybrid_Logger::error( "Exception:" . $e->getMessage(), $e );
	
					Hybrid_Error::setError( $e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e );
	
					$hauth->returnToCallbackUrl();
				}
	
				die();
			}
	
			# define:endpoint step 3.1 and 3.2
			if( isset( $_REQUEST["hauth_done"] ) && $_REQUEST["hauth_done"] ) 
			{
				$provider_id = trim( strip_tags( $_REQUEST["hauth_done"] ) );
	
				$hauth = Hybrid_Auth::setup( $provider_id );
				
				if( ! $hauth )
				{
					Hybrid_Logger::error( "Endpoint: Invalide parameter on hauth_done!" ); 
	
					$hauth->adapter->setUserUnconnected();
	
					header("HTTP/1.0 404 Not Found"); 
	
					die( "Invalide parameter! Please return to the login page and try again." );
				}
	
				try
				{
					Hybrid_Logger::info( "Endpoint: call adapter [{$provider_id}] loginFinish() " );
					
					$hauth->adapter->loginFinish(); 
				}
				catch( Exception $e )
				{
					Hybrid_Logger::error( "Exception:" . $e->getMessage(), $e );
	
					Hybrid_Error::setError( $e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e );
	
					$hauth->adapter->setUserUnconnected(); 
				}
	
				Hybrid_Logger::info( "Endpoint: job done. retrun to callback url." );
	
				$hauth->returnToCallbackUrl();
	
				die();
			}
		}
		else{
			# Else, 
			# We advertise our XRDS document, something supposed to be done from the Realm URL page 
			echo str_replace
				(
					"{X_XRDS_LOCATION}",
					Hybrid_Auth::getCurrentUrl( false ) . "?get=openid_xrds&v=" . Hybrid_Auth::$version,
					file_get_contents( $_SERVER["DOCUMENT_ROOT"] . "/../library/Hybrid/resources/openid_realm.html" )
				); 
	
			die();
		}
	}
	
	public function loginAction()
	{
		$this->_helper->layout->disableLayout();
		    try 
	    	{
	        // action body
	      $config= array( 
			// set on "base_url" the url that point to HybridAuth Endpoint (where the index.php is found)
			"base_url"         => "http://hoianexpress.a/index/config",
	 
			"providers"      => array (
				// openid
				"OpenID" 		=> 	array ( 
										"enabled" 	=> true // no keys required for OpenID based providers
									),
	
				// google
				"Google" 		=> 	array ( 
										"enabled" 	=> true 
									),
	
				// yahoo
				"Yahoo"             => 	array ( 
										"enabled" 	=> true 
									),
	
				// aol
				"AOL"               => 	array ( // 'devid' is your AOL Developer ID, try "bs1p7S-EREVcBHk3" it may work
										"enabled" 	=> true,
										"keys"	 	=> array ( "devid" => "" ) 
									),
	
				// facebook
				"Facebook" 			=> array ( // 'id' is your facebook application id
										"enabled" 	=> true,
										"keys"	 	=> array ( "id" => "181628681897139", "secret" => "1317acbb93501d00883e3db2fff4945d" ) 
									),
	
				// myspace
				"MySpace" 	        => 	array ( // 'key' is your twitter application consumer key
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// twitter
				"Twitter"   	    => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// windows live
				"Live"  			=> array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "id" => "", "secret" => "" ) 
									),
	
				// linkedin
				"LinkedIn"          => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// viadeo
				"Viadeo"          => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "id" => "", "secret" => "" )
									),
	
				// tumblr
				"Tumblr"            => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// identi.ca
				"Identica"          => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// vimeo
				"Vimeo"             => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// foursquare
				"Foursquare"        => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									), 
	
				// last.fm
				"LastFM"            => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// gowalla
				"Gowalla"           => 	array ( 
										"enabled" 	=> true,
										"keys"	 	=> array ( "key" => "", "secret" => "" )
									),
	
				// PayPal
				"PayPal"  			=> array ( 
										"enabled" 	=> true, 
									),
			),	
			// if you want to enable logging, set 'debug_mode' to true  then provide a writable file by the web server on "debug_file"
			"debug_mode"            => false ,
			"debug_file"            => "", 
		);
		$provider=$this->getRequest()->getParam("provider");
		$hybrid= new Hybrid_Auth($config);
		if($hybrid->isConnectedWith($provider))
		{
			$adaptor = $hybrid->getAdapter($provider);
			$data=$adaptor->getUserProfile();
			$id= md5($data->identifier);
			$user = new Default_Model_DbTable_User();
			if($user->checkexist($id))
			{
				$user->updateInfo($id, $data->email, $data->displayName);
			}else 
			{
				$user->import($id, $data->email, $data->displayName);
			}
			$session = new Zend_Session_Namespace("user");
			$session->id=$id;
			$session->name=$data->displayName;
			$this->view->show='1';
		}else
			$hybrid->authenticate($provider);
	    }	catch (Exception $e)
	    {
	    	echo $e->getMessage();
	    }
	}
}

